//
//  XViewController.m
//  XPhotoLibraryKit
//
//  Created by wuxinting on 03/20/2018.
//  Copyright (c) 2018 wuxinting. All rights reserved.
//

#import "XViewController.h"
#import "XPhotoCollectionCell.h"
#import "XPhotoCollectionSectionHeader.h"
#import <XPhotoLibraryKit/XPhotoModel.h>
#import "XPhotoBrowser.h"
#import "XPhoto.h"
#import "UIImage+Resource.h"
@import SVProgressHUD;

static NSString *ReuseIdentify = @"UICollectionViewForPhoto";
static NSString *ReuseHeaderIdentify = @"UICollectionViewForPhotoHeader";
@interface XViewController () <XPhotoModelDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource, XPhotoBrowserDataSource, XPhotoBrowserDelegate>

@property (nonatomic, strong) XPhotoModel *photoModel;
@property (nonatomic, strong) UICollectionView *photoCollectionView;
@property (nonatomic, strong) XPhotoBrowser *photoBrowser;
@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGR;
@property (nonatomic, assign) BOOL editable;
@property (nonatomic, strong) UIButton *saveBtn;

@end

@implementation XViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationItem setTitle:@"Photo"];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.saveBtn.hidden = YES;
    [self.saveBtn addTarget:self action:@selector(clickSaveButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.saveBtn];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.photoCollectionView.dataSource = self;
    self.photoCollectionView.delegate = self;
    self.photoCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.photoCollectionView];
    [self.photoCollectionView registerClass:[XPhotoCollectionCell class] forCellWithReuseIdentifier:ReuseIdentify];
    [self.photoCollectionView registerClass:[XPhotoCollectionSectionHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ReuseHeaderIdentify];
	
    self.photoBrowser.hidden = YES;
    self.photoBrowser.browserDataSource = self;
    self.photoBrowser.browserDelegate = self;
    [self.navigationController.view addSubview:self.photoBrowser];
    
    self.photoModel.delegate = self;
    [self.photoModel loadPhotos];
    [self.photoCollectionView reloadData];
    
    self.longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGR:)];
    [self.view addGestureRecognizer:self.longPressGR];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.photoCollectionView.frame = self.view.bounds;
}

#pragma mark - XPhotoBrowserDataSource
- (NSUInteger)numberOfPhotosInPhotoBrowser:(XPhotoBrowser *)browser {
    return self.photoModel.totalCount;
}

- (XPhoto *)photoBrowser:(XPhotoBrowser *)browser photoForIndex:(NSUInteger)index {
    return [self.photoModel assetAtIndex:index];
}

#pragma mark - XPhotoBrowserDelegate
- (void)photoBrowser:(XPhotoBrowser *)browser displayItemAtIndex:(NSUInteger)index {
    NSIndexPath *indexPath = [self.photoModel indexPathForIndex:index];
    if (indexPath.section == 0) {
        indexPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:0];
    }
    UICollectionViewCell *cell = [self.photoCollectionView cellForItemAtIndexPath:indexPath];
    if (![self.photoCollectionView.visibleCells containsObject:cell]) {
        [self.photoCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
    }
    [browser animationTargetView:cell];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return MAX(self.photoModel.colls.count, 1);
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0 && self.photoModel.colls.count < 1) {
        return 1; // Camera
    }
    PHAssetCollection *c = [self.photoModel.colls objectAtIndex:section];
    if (section == 0) {
        return [self.photoModel assetsInColl:c].count + 1;
    }
    return [self.photoModel assetsInColl:c].count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    XPhotoCollectionCell *cell = (XPhotoCollectionCell *)[collectionView dequeueReusableCellWithReuseIdentifier:ReuseIdentify forIndexPath:indexPath];
    if (indexPath.row == 0 && indexPath.section == 0) {
        XPhoto *photo = [[XPhoto alloc] init];
        photo.functionalImage = [UIImage imageForName:@"camera"];
        cell.photo = photo;
        cell.editable = NO;
        [cell refresh];
        return cell;
    }
    
    PHAssetCollection *c = [self.photoModel.colls objectAtIndex:indexPath.section];
    NSArray<XPhoto *> *assets = [self.photoModel assetsInColl:c];
    cell.photo = [assets objectAtIndex:(indexPath.row - ((indexPath.section == 0)?1:0))];
    cell.editable = self.editable;
    [cell refresh];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    XPhotoCollectionSectionHeader *secHeader = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ReuseHeaderIdentify forIndexPath:indexPath];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    if (indexPath.section == 0 && self.photoModel.colls.count < 1) {
        secHeader.title = [formatter stringFromDate:[NSDate date]];
        [secHeader refresh];
        return secHeader;
    }
    
    PHAssetCollection *coll = [self.photoModel.colls objectAtIndex:indexPath.section];
    secHeader.title = [formatter stringFromDate:coll.startDate];
    
    if (indexPath.section == 0) {
        secHeader.bannerString = @"图片浏览器";
    } else {
        secHeader.bannerString = nil;
    }
    [secHeader refresh];
    return secHeader;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake([self cellSize], [self cellSize]);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    CGFloat headerHeight = 40;
    if (section == 0) {
        headerHeight = 140;
    }
    return CGSizeMake(collectionView.bounds.size.width, headerHeight);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, [self cellPadding], 0, [self cellPadding]);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return [self cellPadding];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return [self cellPadding];
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        // Camera
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
        return;
    }
    UIView *sourceView = [collectionView cellForItemAtIndexPath:indexPath];
    [self.photoBrowser animationSourceView:sourceView];
    [self.photoBrowser animationTargetView:sourceView];
    
    
    if (indexPath.section == 0) {
        indexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0];
    }
    self.photoBrowser.currentIndex = [self.photoModel indexForIndexPath:indexPath];
    [self.photoBrowser reloadData];
    self.photoBrowser.hidden = NO;
}

#pragma mark - XPhotoModelDelegate
- (void)photoModel:(XPhotoModel *)photoModel loadFinished:(NSArray *)photos {
    
}

#pragma mark - Action
- (void)clickSaveButton:(UIButton *)btn {
    self.editable = NO;
    self.saveBtn.hidden = !self.editable;
    [self.photoModel saveChecked:^{
        [SVProgressHUD showSuccessWithStatus:@"保存完成"];
        [SVProgressHUD dismissWithDelay:0.5];
    }];
    
    for (UICollectionViewCell *cell in self.photoCollectionView.visibleCells) {
        if (![cell isKindOfClass:[XPhotoCollectionCell class]]) continue;
        
        XPhotoCollectionCell *pcCell = (XPhotoCollectionCell *)cell;
        pcCell.editable = self.editable;
    }
}

- (void)longPressGR:(UILongPressGestureRecognizer *)gr {
    self.editable = YES;
    self.saveBtn.hidden = !self.editable;
    
    for (UICollectionViewCell *cell in self.photoCollectionView.visibleCells) {
        if (![cell isKindOfClass:[XPhotoCollectionCell class]]) continue;
        
        XPhotoCollectionCell *pcCell = (XPhotoCollectionCell *)cell;
        pcCell.editable = self.editable;
    }
}

#pragma mark - Private
- (CGFloat)cellSize {
    // 以iPhone6的屏幕(375)为标准，适配屏幕。Cell的size与边距定30倍
    static CGFloat sCellSize = -1;
    if (sCellSize < 0) {
        CGFloat width = [UIScreen mainScreen].bounds.size.width;
        CGFloat ratio = width / 375;
        CGFloat expectSize = floor(ratio) * 100.f;
        CGFloat cpRatio = 30.f;
        NSInteger num = floor((width - expectSize / cpRatio) / ((cpRatio + 1) * expectSize / cpRatio));
        sCellSize = (width * cpRatio) / ((cpRatio + 1) * num + 1);
    }
    return sCellSize;
}

- (CGFloat)cellPadding {
    CGFloat cpRatio = 30;
    return [self cellSize] / cpRatio;
}

#pragma mark - Get&Set
- (XPhotoModel *)photoModel {
    if (!_photoModel) {
        _photoModel = [[XPhotoModel alloc] init];
    }
    return _photoModel;
}

- (XPhotoBrowser *)photoBrowser {
    if (!_photoBrowser) {
        _photoBrowser = [[XPhotoBrowser alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _photoBrowser;
}

- (UICollectionView *)photoCollectionView {
    if (!_photoCollectionView) {
        CGRect frame = CGRectInset(self.view.bounds, 0, self.navigationController.navigationBar.bounds.size.height);
        _photoCollectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    }
    return _photoCollectionView;
}

- (UIButton *)saveBtn {
    if (!_saveBtn) {
        _saveBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        [_saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    }
    return _saveBtn;
}

@end
